<?php
/**
 * UserAssetRepo.php
 * ==============================================
 * Copy right 2015-2022  by https://www.tianmtech.com/
 * ----------------------------------------------
 * This is not a free software, without any authorization is not allowed to use and spread.
 * ==============================================
 *
 * @desc : 用户资产表
 * @author: zhanglinxiao<zhanglinxiao@tianmtech.cn>
 * @date: 2022/01/17
 * @version: v1.0.0
 * @since: 2021/01/17 09:11
 */

namespace App\Repositories;

use App\Models\MainDB\UserAsset;
use Illuminate\Support\Facades\DB;

class UserAssetRepo
{

    /**
     * @var UserAsset
     */
    protected $model;

    public function __construct()
    {
        $this->model=app("model_user_asset");
    }

    //获取用户可提现收益
    public function getUserWithdrawableEarnings($user_id)
    {
        $earnings = $this->model->newQuery()->where('user_id', $user_id)->value('withdrawable_earnings');

        return $earnings > 0 ? $earnings : 0;
    }

    /**
     * 变更用户收益
     *
     * @param  int $userId
     * @param  float $earnings
     * @param  int $symbol 增加还是减少：0-减少；1-增加；
     * @return int
     */
    public function changeUserWithdrawableEarnings($userId, $earnings, $symbol)
    {
        $earnings = abs($earnings);
        $model = $this->model;


        if ($symbol == 1) {//增加
            $result = $model->newQuery()
                ->where('user_id', $userId)
                ->update([
                    'withdrawable_earnings' => DB::raw("withdrawable_earnings + {$earnings}"
                    ),
                ]);
        } else {//减少
            $query = $model->newQuery()
                ->where('user_id', $userId);

            $result = $query->update([
                'withdrawable_earnings' => DB::raw("withdrawable_earnings - {$earnings}"
                ),
            ]);
        }

        return $result;
    }

    /**
     * 更新或插入数据
     * @param $userId
     * @param $data
     */
    public function updateOrCreate($userId, $data)
    {
        $this->model->newQuery()->updateOrInsert(array('user_id' => $userId), $data);
    }


    /**
     * 通过用户ID批量删除
     * @param $userIds
     */
    public function deleteByUserIds($userIds)
    {
        $this->model->newQuery()->whereIn('user_id', $userIds)->delete();
    }


}
